package cn.thornbird.orgsync.repository.specification;

import cn.thornbird.orgsync.entity.Company;
import cn.thornbird.orgsync.vo.request.CompanyQueryRequest;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@AllArgsConstructor
public class CompanySpecification extends BaseSpecification<Company>  {

    private static final long serialVersionUID = 6176030618643992643L;

    private final CompanyQueryRequest companyQueryRequest;

    private final String creatorUsername;

    @Override
    public Predicate toPredicate(@NonNull Root<Company> root, @NonNull CriteriaQuery<?> query,
                                 @NonNull CriteriaBuilder criteriaBuilder) {
        List<Predicate> predicates = new ArrayList<>();
        List<String> fields = Arrays.asList("name", "address", "website", "email", "telephone");
        predicates.add(toKeywordPredicate(companyQueryRequest.getKeyword(), fields, root, criteriaBuilder));
        predicates.add(createEqualPredicate(root, criteriaBuilder, "active", companyQueryRequest.getActive()));
        if (!StringUtils.isEmpty(companyQueryRequest.getCityId())) {
            predicates.add(criteriaBuilder.equal(root.get("cityId"), companyQueryRequest.getCityId()));
        }
        if (companyQueryRequest.getOwner() != null) {
            String username = creatorUsername == null ? "" : creatorUsername;
            if (companyQueryRequest.getOwner()) {
                predicates.add(criteriaBuilder.equal(root.get("createdBy"), username));
            } else {
                predicates.add(criteriaBuilder.notEqual(root.get("createdBy"), username));
            }
        }
        return toPredicate(criteriaBuilder, predicates);
    }

}
